package com.mxx.common.thread;

/**
 * @author: mxx
 * @date: 2021/8/19
 * @time: 11:16
 * @Description: 描述信息
 */

import com.mxx.common.core.BTConsumer;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Function;

/**
 * 数据分化后批次处理
 *
 * @param <T>
 */
@Slf4j
public class BatchList<T> implements Runnable {
    private List<T> batchDataList;
    private int batchStart;
    private BiConsumer<List<T>, Integer> consumer;

    /**
     * @param batchDataList 批数据集合
     * @param batchStart    批数据起始位置
     * @param consumer      执行方法
     */

    public BatchList(List<T> batchDataList, int batchStart, BiConsumer<List<T>, Integer> consumer) {
        this.batchDataList = batchDataList;
        this.batchStart = batchStart;
        this.consumer = consumer;
    }

    @Override
    public void run() {
        try {
            consumer.accept(batchDataList, batchStart);
        } catch (Exception ex) {
            log.info("execute batchList exception ", ex);
        }
    }


    public static <T> void batch(List<T> batchDataList, int batchNumber, BiConsumer<List<T>, Integer> consumer) {
        int start = 0;
        int end = batchNumber;
        while (start < batchDataList.size()) {
            if (end >= batchDataList.size()) {
                end = batchDataList.size();
            }
            consumer.accept(batchDataList.subList(start, end), start);
            start = end;
            end += batchNumber;
        }
    }
}